<template>
  <div class="factory-brand-info app-container" v-loading="loading">
    <a-spin dot :loading="loading" style="height: 100%">
      <!-- <a-button type="primary" @click="getFormData">获取brand表单数据</a-button> -->
      <div class="action-wrap">
        <a-button class="mr16" @click="cancel">取消</a-button>
        <a-button type="primary" @click="saveCom">保存</a-button>
      </div>

      <p class="title mt20">商品资质资料</p>
      <a-form ref="formRef" auto-label-width :model="form" :style="{ width: '90%' }" v-if="reload">
        <a-row :gutter="200">
          <a-col :span="24">
            <a-form-item
              field="brand"
              label="旗下品牌"
              :rules="[{ required: true, message: '请输入' }]"
              :validate-trigger="['blur']"
            >
              <div style="width: 100%">
                <!-- <a-input v-show="false" v-model="form.brand"></a-input> -->
                <div class="brand-wrap mb20">
                  <div>
                    <a-input v-model="form.bandName" disabled placeholder="请输入" :min="0" />
                  </div>
                  <div class="brand-icon-wrap">
                    <div>
                      <a-upload
                        class="area-upload card-area-upload mr50 mt16"
                        action="/"
                        :auto-upload="false"
                        :show-file-list="false"
                        ref="uploadBrandIconRef"
                        @change="
                          (files, file) => {
                            handleAvatarChangeIcon('bandPicId', files, file, null, false, 'img');
                          }
                        "
                      >
                        <template #upload-button>
                          <a-space v-if="!(form?._bandPicId || form?.bandPicUrl)">
                            <a-button type="text">
                              <div>
                                <IconPlus />
                                <p class="f12">上传商标</p>
                              </div>
                            </a-button>
                          </a-space>
                          <img v-else :src="form?._bandPicId || form?.bandPicUrl" alt="" />
                          <!--  :src="form?._bandPicId || form.brandList.length > 0 ? form.brandList[0].bandPicUrl : ''" -->
                        </template>
                      </a-upload>
                    </div>
                    <div>
                      <a-upload
                        :file-list="form.bandFileIdFileList"
                        class="area-upload card-area-upload mt16"
                        action="/"
                        :auto-upload="false"
                        :show-file-list="false"
                        ref="uploadBrandRef"
                        @change="
                          (files, file) => {
                            handleAvatarChangeIcon('bandFileId', files, file, null, false, 'all', 'bandFileId');
                          }
                        "
                      >
                        <template #upload-button>
                          <a-space v-if="!form?.bandFileId">
                            <a-button type="text">
                              <icon-upload />
                              <p class="f12">上传文件</p>
                            </a-button>
                          </a-space>

                          <div v-else style="width: 100%">
                            <div
                              class="pl20 pr20"
                              style="
                                width: 100%;
                                display: flex;
                                flex-direction: column;
                                justify-content: space-between;
                                box-sizing: border-box;
                                align-items: center;
                              "
                            >
                              <p
                                class="text-over"
                                style="width: 100%"
                                :title="
                                  (form._bandFileId
                                    ? decodeURIComponent(form._bandFileId.split('/')[form._bandFileId.split('/').length - 1])
                                    : '') ||
                                  (form.bandFileUrl
                                    ? decodeURIComponent(form.bandFileUrl.split('/')[form.bandFileUrl.split('/').length - 1])
                                    : '')
                                "
                              >
                                {{
                                  (form._bandFileId
                                    ? decodeURIComponent(form._bandFileId.split("/")[form._bandFileId.split("/").length - 1])
                                    : "") ||
                                  (form.bandFileUrl
                                    ? decodeURIComponent(form.bandFileUrl.split("/")[form.bandFileUrl.split("/").length - 1])
                                    : "")
                                }}
                              </p>
                              <div
                                classs="btn-wrap"
                                style="
                                  width: 100%;
                                  display: flex;
                                  justify-content: space-between;
                                  box-sizing: border-box;
                                  align-items: center;
                                "
                              >
                                <a-button type="text" class="mb4"> 重新上传 </a-button>
                                <a-button type="text" @click.stop="downloadFile(form.bandFileUrl || form?._bandFileId)"
                                  >下载</a-button
                                >
                              </div>
                            </div>
                          </div>
                        </template>
                      </a-upload>
                    </div>
                  </div>
                </div>
              </div>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item field="enTestCertificate" label="环保检测证书">
              <div style="width: 100%">
                <a-upload
                  :file-list="form.envCertificationsPicUrls"
                  class="area-upload card-area-upload yc-upload jzt-arco-upload"
                  action="/"
                  :auto-upload="false"
                  ref="uploadycIconRef"
                  list-type="picture-card"
                  image-preview
                  :show-remove-button="true"
                  :show-retry-button="false"
                  :show-cancel-button="false"
                  :show-upload-button="false"
                  :show-preview-button="false"
                  multiple
                  :limit="8"
                  @change="
                    (files, file) => {
                      handleAvatarChangeIcon(
                        'envCertificationsPicIds',
                        files,
                        file,
                        null,
                        true,
                        'img',
                        'envCertificationsPicUrls'
                      );
                    }
                  "
                >
                  <template #upload-button>
                    <a-space>
                      <a-button type="text" :disabled="form.envCertificationsPicIds?.length >= 8" class="upload-btn">
                        <div><IconPlus /></div>
                      </a-button>
                    </a-space>
                  </template>
                </a-upload>
                <p class="f12 mt10" style="color: #86909c">
                  量最多8张，单张不超过10M,支持jpeg，jpg，png格式;主题鲜明、图片清晰。
                </p>
              </div>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item field="qualityReport" label="商品质量检测报告">
              <div style="width: 100%">
                <a-upload
                  :file-list="form.quaCheckPicUrls"
                  class="area-upload card-area-upload yc-upload jzt-arco-upload"
                  action="/"
                  :auto-upload="false"
                  ref="uploadycIconRef"
                  list-type="picture-card"
                  image-preview
                  :show-remove-button="true"
                  :show-retry-button="false"
                  :show-cancel-button="false"
                  :show-upload-button="false"
                  :show-preview-button="false"
                  multiple
                  :limit="8"
                  @change="
                    (files, file) => {
                      handleAvatarChangeIcon('quaCheckPicIds', files, file, null, true, 'img', 'quaCheckPicUrls');
                    }
                  "
                >
                  <template #upload-button>
                    <a-space>
                      <a-button type="text" :disabled="form.quaCheckPicIds?.length >= 8" class="upload-btn">
                        <div><IconPlus /></div>
                      </a-button>
                    </a-space>
                  </template>
                </a-upload>
                <p class="f12 mt10" style="color: #86909c">
                  量最多8张，单张不超过10M,支持jpeg，jpg，png格式;主题鲜明、图片清晰。
                </p>
              </div>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item field="brandLetter" label="品牌授权书">
              <div style="width: 100%">
                <a-upload
                  :file-list="form.bandPutPicUrls"
                  class="area-upload card-area-upload yc-upload jzt-arco-upload"
                  action="/"
                  :auto-upload="false"
                  ref="uploadycIconRef"
                  list-type="picture-card"
                  image-preview
                  :show-remove-button="true"
                  :show-retry-button="false"
                  :show-cancel-button="false"
                  :show-upload-button="false"
                  :show-preview-button="false"
                  multiple
                  :limit="8"
                  @change="
                    (files, file) => {
                      handleAvatarChangeIcon('bandPutPicIds', files, file, null, true, 'img', 'bandPutPicUrls');
                    }
                  "
                >
                  <template #upload-button>
                    <a-space>
                      <a-button type="text" :disabled="form.bandPutPicIds?.length >= 8" class="upload-btn">
                        <div><IconPlus /></div>
                      </a-button>
                    </a-space>
                  </template>
                </a-upload>
                <p class="f12 mt10" style="color: #86909c">
                  量最多8张，单张不超过10M,支持jpeg，jpg，png格式;主题鲜明、图片清晰。
                </p>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- ================================================================================================================== -->
      <p class="title mt55">品牌介绍<span class="f12" style="color: #86909c">（支持编辑图片、视频、文本、表格、多样化）</span></p>
      <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="'default'" />
        <Editor
          style="height: 500px; overflow-y: hidden"
          v-model="valueHtml"
          :defaultConfig="editorConfig"
          :mode="'simple'"
          @onCreated="handleCreated"
        />
      </div>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import { IconPlusCircleFill, IconDelete, IconUpload, IconPlus } from "@arco-design/web-vue/es/icon";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { Message } from "@arco-design/web-vue";
import { saveBrandInfo } from "@/apis/business";
import { useRoute } from "vue-router";
const route = useRoute();

const emit = defineEmits(["cancel"]);
const form = ref<any>({});
const _detailInfo = ref({});
const reload = ref(true);
const loading = ref(false);

const props = defineProps({
  detailInfo: {
    type: Object,
    default: () => {}
  }
});

watch(
  () => props.detailInfo,
  val => {
    if (val) {
      setTimeout(() => {
        _detailInfo.value = JSON.parse(JSON.stringify(val));
        editReview();
      }, 10);
    }
  },
  { deep: true }
);

const cancel = () => {
  emit("cancel");
};

const reloadY = () => {
  loading.value = true;
};
const reloadN = () => {
  loading.value = false;
};

const reset = data => {
  editReview();
};

const saveCom = () => {
  const data = getFormData();
  saveBrandInfo({ ...props.detailInfo, ...data, factoryId: route.query.factoryId }).then(res => {
    if (res.code === 200) {
      Message.success("品牌信息保存成功");
    }
  });
};
const editReview = () => {
  // 编辑的时候，数据回显
  console.log("账户信息回显===", _detailInfo.value);
  form.value = { ..._detailInfo.value };
  let _envCertificationsPicUrls = [];
  let _quaCheckPicUrls = [];
  let _bandPutPicUrls = [];
  _envCertificationsPicUrls = form.value?.envCertificationsPicUrls?.map((item, index) => {
    return {
      url: item,
      uid: form.value.envCertificationsPicIds[index]
    };
  });
  _quaCheckPicUrls = form.value?.quaCheckPicUrls?.map((item, index) => {
    return {
      url: item,
      uid: form.value.quaCheckPicIds[index]
    };
  });
  _bandPutPicUrls = form.value?.bandPutPicUrls?.map((item, index) => {
    return {
      url: item,
      uid: form.value.bandPutPicIds[index]
    };
  });

  form.value.envCertificationsPicUrls = _envCertificationsPicUrls || [];
  form.value.quaCheckPicUrls = _quaCheckPicUrls || [];
  form.value.bandPutPicUrls = _bandPutPicUrls || [];
  valueHtml.value = form.value.content || "";

  reloadN();
  console.log("envCertificationsPicUrls", form.value.envCertificationsPicUrls);
};

//====================================富文本编辑器========================================================================================

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("");
const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file, insertFn) => {
        // console.log("触发图片上传");
        await handleAvatarChangeIcon2(file);
        // console.log("上传图片的地址===", imgUrl.value);
        insertFn(imgUrl.value.split("?")[0]); // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
      }
    },
    uploadVideo: {
      customUpload: async (file, insertFn) => {
        // console.log("触发视频上传");
        await handleAvatarChangeIcon2(file, "video");
        // console.log("上传视频的地址===", videoUrl.value);
        insertFn(videoUrl.value.split("?")[0]); // 最后插入视频 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
      }
    }
  }
};
const imgUrl = ref(""); //编辑器每选择一次图片，上传后的地址
const videoUrl = ref(""); //编辑器每选择一次视频，上传后的地址

const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const handleAvatarChangeIcon2 = async (file, type = "img") => {
  //选中文件触发的change事件
  // console.log(file);
  await customUpload2({ file }, type);
};
/**
 * 富文本上传
 */
const customUpload2 = async (option, type) => {
  const folder = getFolder();
  // const objName = folder + option.file.name;
  const objName = folder + option.file.name.split(".")[0] + new Date().getTime() + "." + option.file.name.split(".")[1];

  await ossStore
    .submit(objName, option.file)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl);
      if (type === "img") {
        imgUrl.value = res.fileUrl.split("?")[0];
      } else {
        videoUrl.value = res.fileUrl.split("?")[0];
      }
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const getFormData = () => {
  const brandinfo = {
    bandName: props.detailInfo.bandName,
    bandFileId: form.value?.bandFileId,
    bandFileUrl: form.value?._bandFileId || form.value?.bandFileUrl,
    bandPicId: form.value?.bandPicId,
    bandPicUrl: form.value?._bandPicId || form.value?.bandPicUrl,

    envCertificationsPicIds: form.value?.envCertificationsPicIds, //环保检测证书id
    envCertificationsPicUrls: form.value?._envCertificationsPicIds, //环保检测证书url
    quaCheckPicIds: form.value?.quaCheckPicIds, //质量检测报告id
    quaCheckPicUrls: form.value?._quaCheckPicIds, //质量检测报告url
    bandPutPicIds: form.value?.bandPutPicIds, //品牌授权id
    bandPutPicUrls: form.value?._bandPutPicIds, //品牌授权url
    content: valueHtml.value //富文本内容
  };
  // console.log(111111111111, form.value, brandinfo);
  return brandinfo;
};
const getFormData2 = () => {
  const brandinfo = {
    envCertificationsPicIds: form.value?.envCertificationsPicIds, //环保检测证书id
    envCertificationsPicUrls: form.value?._envCertificationsPicIds, //环保检测证书url
    quaCheckPicIds: form.value?.quaCheckPicIds, //质量检测报告id
    quaCheckPicUrls: form.value?._quaCheckPicIds, //质量检测报告url
    bandPutPicIds: form.value?.bandPutPicIds, //品牌授权id
    bandPutPicUrls: form.value?._bandPutPicIds, //品牌授权url
    content: valueHtml.value //富文本内容
  };
  // console.log(111111111111, form.value, brandinfo);
  return brandinfo;
};
defineExpose({
  getFormData: getFormData2,
  reset,
  reloadY,
  reloadN
});
//====================================文件上传========================================================================================

import useMultipartOssStore from "@/stores/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import { getFolder, _debounce } from "@/utils/index";
import { imgsUploadFac } from "@/apis";
import { factory } from "typescript";
const fileList = ref({});

const handleAvatarChangeIcon = _debounce(
  async (key: string, files: any, file: any, item?: any, multiple = false, type = "all", speKey?: string) => {
    //选中文件触发的change事件
    let doneFiles = [];
    if (!multiple) {
      // 不是多选，清空文件列表
      fileList.value[key + "FileList"] = [];
    } else {
      // 多选，清空form里面存的对应值[]
      form.value[key] = [];
      form.value["_" + key] = [];
      doneFiles = files.filter(item => item.status === "done");
      console.log("files===", files);
      console.log("已经存在的图片===", doneFiles);
      for (let item of doneFiles) {
        form.value[key].push(item.uid);
        form.value["_" + key].push(item.url);
      }
    }

    let _files = files.filter(item => item.status !== "done");
    //文件格式校验
    const flag = fileType(type, !multiple ? [file] : _files);
    if (!flag) {
      let normalFiles = [];
      if (type === "img") {
        Message.error("只能上传图片文件");
        normalFiles = _files.filter(item => {
          if ((item.file && (item.file.type === "image/jpeg" || item.file.type === "image/png")) || !item.file) {
            return item;
          }
        });
        if (speKey) {
          form.value[speKey] = [...doneFiles, ...normalFiles];
        }
      }
      if (normalFiles.length <= 0) {
        return;
      } else {
        if (!multiple) return;
        _files = normalFiles;
      }
    }
    // console.log("准备上传的文件===", _files);
    if (!multiple) {
      await customUpload({ file: file }, item, key, multiple);
    } else {
      for (let obj of _files) {
        await customUpload({ file: obj }, item, key, multiple);
      }
    }
  },
  100
);

/**
 * 校验文件类型
 */
const fileType = (type, fileList) => {
  console.log(90909090, fileList);
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!(item.file.type === "image/jpeg" || item.file.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "video") {
    for (let item of fileList) {
      if (!(item.raw.type === "video/mp4")) {
        flag = false;
      }
    }
  }
  return flag;
};
/**
 * 上传
 */
const customUpload = async (option, item, key, multiple) => {
  const folder = getFolder();
  const objName = folder + option.file.name;
  await ossStore
    .submit(objName, option.file.file)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl.split("?")[0]);
      const temp = String(new Date().getTime());
      const num = String(Math.floor(Math.random() * (99 - 10 + 1)) + 10);
      const uid = Number(temp + num);
      if (item) {
        item[key] = uid;
        item["_" + key] = res.fileUrl.split("?")[0];
      } else {
        if (multiple) {
          form.value[key].push(uid);
          form.value["_" + key].push(res.fileUrl.split("?")[0]);
        } else {
          form.value[key] = uid;
          form.value["_" + key] = res.fileUrl.split("?")[0];
        }
      }
      uploadIMG(option, objName, res.fileUrl.split("?")[0], uid); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
//将图片上传到业务端服务
const uploadIMG = (option, objName, url, uid) => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: uid,
      objectName: objName, //目录＋文件名称
      url: url,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUploadFac(uploadArr);
};
/**
 * 下载附件
 */
const downloadFile = url => {
  console.log("这是下载附件操作", url);
  const urlSplit = url ? url.split("/") : [];
  const name = decodeURIComponent(urlSplit[urlSplit.length - 1]);
  let xhr = new XMLHttpRequest();
  xhr.open("get", url, true);
  xhr.responseType = "blob";
  xhr.onload = function (e) {
    if (xhr.status === 200) {
      let file = xhr.response;
      let fileName = name;
      if ("msSaveOrOpenBlob" in navigator) {
        window.navigator.msSaveOrOpenBlob(file, fileName);
      } else {
        let fileUrl = window.URL.createObjectURL(file);
        let a = document.createElement("a");
        a.download = fileName;
        a.href = fileUrl;
        document.getElementsByTagName("body")[0].appendChild(a);
        a.click();
        a.parentNode.removeChild(a);
        window.URL.revokeObjectURL(fileUrl);
      }
    }
  };
  xhr.send();
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>

<style lang="scss" scoped>
.action-wrap {
  display: flex;
  justify-content: flex-end;
  padding: 16px 20px;
  z-index: 2;
  background-color: white;
  position: absolute;
  bottom: 0;
  right: 0;
  left: 201px;
  box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
}
:deep(.arco-input-wrapper.arco-input-disabled) {
  background-color: white;
}
:deep(.w-e-textarea-video-container) {
  video {
    width: 100%;
  }
}
:deep(.arco-btn.upload-btn) {
  width: 80px;
  height: 80px;
}
p.title {
  font-size: 18px;
  color: #131414;
  margin-bottom: 24px;
}
.brand-icon-wrap {
  display: flex;
  & > div {
    width: 200px;
    margin-right: 50px;
    & > p {
      word-wrap: break-word;
    }
  }
  .arco-upload-wrapper.arco-upload-wrapper-type-text.area-upload.card-area-upload {
    width: 100px;
    height: 100px;
    .arco-upload {
      height: 100%;
      padding: 0;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.yc-upload {
  width: 100%;
  .arco-upload {
    width: 100px;
    height: 100px;
    display: flex !important;
    align-items: center;
    justify-content: center;
  }
  .arco-upload-list-picture {
    width: 100px;
    height: 100px;
  }
  .arco-upload-list.arco-upload-list-type-picture-card {
    width: 100%;
    .arco-upload.arco-upload-type-picture-card.arco-upload-hide {
      width: 100px;
    }
  }
}
.area-upload {
  :deep(.arco-upload) {
    display: inline-block;
    box-sizing: border-box;
    background-color: #f2f3f5;
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  :deep(.arco-upload-list) {
    .arco-upload-list-item {
      margin-top: 2px;
    }
    .arco-upload-list-item-operation,
    .arco-upload-progress {
      display: none;
    }
  }
}
:deep(.card-area-upload) {
  &.arco-upload.area-upload {
    display: inline-block;
    box-sizing: border-box;
    background-color: #f2f3f5;
    width: 200px;
    height: 120px;
    & > span {
      display: inline-block;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      .img-wrap {
        width: 100%;
        height: 100%;
      }
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}
.factory-brand-info.app-container {
  padding-top: 0 !important;
  padding-bottom: 84px;
}
</style>
